package com.yyfax.ph.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseFragment;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.utils.RcmPermissionHelper;
import com.yyfax.ph.common.widgets.MarqueeView;
import com.yyfax.ph.common.widgets.RedDotView;
import com.yyfax.ph.common.widgets.autoscrollviewpager.AutoScrollViewPager;
import com.yyfax.ph.common.widgets.circleindicator.CircleIndicator;
import com.yyfax.ph.home.banner.BannerModel;
import com.yyfax.ph.home.banner.BannerPresenter;
import com.yyfax.ph.home.banner.ImagePagerAdapter;
import com.yyfax.ph.home.recommendlas.LASScanRecommendActivity;
import com.yyfax.ph.home.recommendlas.RecommendLasNoOpenActivity;
import com.yyfax.ph.home.recommendlas.RecommendLasTimesOverTopActivity;
import com.yyfax.ph.home.recommendloan.RecommendPermissionModel;
import com.yyfax.ph.home.recommendloan.RecommendPermissionPresenter;
import com.yyfax.ph.home.todolist.ToDoListActivity;
import com.yyfax.ph.home.todolist.ToDoListSizePresenter;
import com.yyfax.ph.personal.authority.login.LoginActivity;
import com.yyfax.ph.personal.message.MessageActivity;
import com.yyfax.ph.personal.message.MsgModel;
import com.yyfax.ph.personal.message.MsgPresenter;
import com.yyfax.ph.web.WebActivity;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页推荐页面
 */
public class HomeFragment extends BaseFragment implements RecommendPermissionPresenter.View, BannerPresenter.View, ToDoListSizePresenter.View, MsgPresenter.View, AdNoticePresenter.View , ImagePagerAdapter.PositionListener {
	private static final String TAG = HomeFragment.class.getSimpleName();
	private static final int LOADER_ID_PERMISSION = 1001;
	private static final int LOADER_ID_AD = 1002;
	private static final int LOADER_ID_MSG = 1003;
	private static final int LOADER_ID_TODO_LIST_SIZE = 1004;
	private static final int LOADER_ID_AD_NOTICES = 1005;
	@BindView(R.id.auto_view_pager)
	AutoScrollViewPager mAutoViewPager;
	@BindView(R.id.view_pager_indicator)
	CircleIndicator mIndicator;
	@BindView(R.id.msg_iv)
	ImageView mMsgIv;
	@BindView(R.id.msg_red_dot_view)
	RedDotView mMsgRedDotView;
	@BindView(R.id.question_help_ll)
	LinearLayout mQuestionHelpLl;
	@BindView(R.id.todo_list_ll)
	RelativeLayout mToDoListLl;
	@BindView(R.id.recommend_loan_ll)
	LinearLayout mRecommendLoanLl;
	@BindView(R.id.btn_recommend_loan)
	Button mBtnRecommendLoan;
	@BindView(R.id.todo_list_tips_tv)
	TextView mTodoListTipsTv;
	@BindView(R.id.marquee_view)
	MarqueeView mMarqueeView;

	Unbinder mUnbinder;
	private ImagePagerAdapter mAdapter;
	private RecommendPermissionPresenter mRcmPermissionPresenter;//推荐贷款权限
	private BannerPresenter mBannerPresenter;//首页图片
	private MsgPresenter mMsgPresenter; // 消息
	private ToDoListSizePresenter mToDoListSizePresenter; // 待办事项数目
	private AdNoticePresenter mAdNoticePresenter;
	private List<BannerModel.BannerBean> mBannerData;
	private String mTodoListSize = "";
	List<String> mAdNotices = new ArrayList<>();

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		getLoaderManager().initLoader(LOADER_ID_PERMISSION, null, this);
		getLoaderManager().initLoader(LOADER_ID_AD, null, this);
		getLoaderManager().initLoader(LOADER_ID_MSG, null, this);
		getLoaderManager().initLoader(LOADER_ID_TODO_LIST_SIZE, null, this);
		getLoaderManager().initLoader(LOADER_ID_AD_NOTICES, null, this);
	}

	@Override
	public void onStart() {
		super.onStart();
		loadBanner();
		if (mAdNoticePresenter != null){
			mAdNoticePresenter.getAdNotice();
		}
		refreshRealTimeData();
		mMarqueeView.startFlipping();
	}

	/**
	 * 刷新需要实时更新的数据.
	 */
	public void refreshRealTimeData(){
		if (YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			if (mToDoListSizePresenter != null) {
				mToDoListSizePresenter.getToDoListSize();
			}
			if (mMsgPresenter != null) {
				mMsgPresenter.getMsgStatus();
			}
		}else {
			setMsgRead(true);
			resolveToDoListNum("0");
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		mMarqueeView.stopFlipping();
	}

	@Override
	public void onResume() {
		super.onResume();
		mAutoViewPager.startAutoScroll();
	}

	@Override
	public void onPause() {
		super.onPause();
		mAutoViewPager.stopAutoScroll();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_PERMISSION);
		getLoaderManager().destroyLoader(LOADER_ID_AD);
		getLoaderManager().destroyLoader(LOADER_ID_MSG);
		getLoaderManager().destroyLoader(LOADER_ID_TODO_LIST_SIZE);
		getLoaderManager().destroyLoader(LOADER_ID_AD_NOTICES);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_PERMISSION:
				return new PresenterLoader<>(getActivity(), new RecommendPermissionPresenter.Generator());
			case LOADER_ID_AD:
				return new PresenterLoader<>(getActivity(), new BannerPresenter.Generator());
			case LOADER_ID_MSG:
				return new PresenterLoader<>(getActivity(), new MsgPresenter.Generator());
			case LOADER_ID_TODO_LIST_SIZE:
				return new PresenterLoader<>(getActivity(), new ToDoListSizePresenter.Generator());
			case LOADER_ID_AD_NOTICES:
				return new PresenterLoader<>(getActivity(), new AdNoticePresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_PERMISSION:
				mRcmPermissionPresenter = (RecommendPermissionPresenter) data;
				mRcmPermissionPresenter.attach(this);
				break;
			case LOADER_ID_AD:
				mBannerPresenter = (BannerPresenter) data;
				mBannerPresenter.attach(this);
				break;
			case LOADER_ID_MSG:
				mMsgPresenter = (MsgPresenter) data;
				mMsgPresenter.attach(this);
				break;
			case LOADER_ID_TODO_LIST_SIZE:
				mToDoListSizePresenter = (ToDoListSizePresenter) data;
				mToDoListSizePresenter.attach(this);
				break;
			case LOADER_ID_AD_NOTICES:
				mAdNoticePresenter = (AdNoticePresenter) data;
				mAdNoticePresenter.attach(this);
				mAdNoticePresenter.getAdNotice();
				break;
			default:
				break;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, null);
		mUnbinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mAdapter = new ImagePagerAdapter(getActivity());
		mAdapter.setPositionListener(this);
	}

	@Override
	public void getAdNoticeSuccess(List<String> adNoticeList) {
		mMarqueeView.stopFlipping();
		mAdNotices.clear();
		if (adNoticeList.size() > 0){
			if (!mAdNotices.containsAll(adNoticeList)){
				mAdNotices.addAll(adNoticeList);
				mMarqueeView.startWithList(mAdNotices);
			}
		}else {
			resolveAdNoticeEmpty();
		}
	}

	@Override
	public void getAdNoticeFailed() {
		resolveAdNoticeEmpty();
	}

	private void resolveAdNoticeEmpty(){
		int adNoticeSize = mAdNotices.size();
		if (adNoticeSize <= 0){
			mAdNotices.add(getString(R.string.default_ad_notice));
			mMarqueeView.startWithList(mAdNotices);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		resolveAdNoticeEmpty();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbinder.unbind();
	}

	@OnClick({R.id.msg_iv, R.id.question_help_ll, R.id.todo_list_ll, R.id.recommend_loan_ll, R.id.btn_recommend_loan})
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.question_help_ll) { // 常见问题
			StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_A002);
			WebActivity.start(getActivity(), getString(R.string.common_problem), WebActivity.TYPE_COMMON_PROBLEM);
			return;
		}

		// 如果已经登录并且保存的登录标识为2则途径资格失效 弹出提示
		if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			LoginActivity.start(getActivity());
			return;
		}
		switch (id) {
			case R.id.msg_iv: // 消息按钮
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_A005);
				MessageActivity.start(getActivity());
				break;
			case R.id.recommend_loan_ll: // 云贷推荐 按钮
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_A004);
				mRcmPermissionPresenter.getLASShareUrl();
				break;
			case R.id.btn_recommend_loan: // 立即推荐 按钮
				mRcmPermissionPresenter.getRcmPermission();//获取推荐权限
				break;
			case R.id.todo_list_ll: // 待办事项按钮
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_A003);
				ToDoListActivity.start(getActivity(), mTodoListSize);
				break;
			default:
				break;
		}
	}

	/**
	 * 跳转云贷扫码推荐
	 */
	public void goToLASScanRecommend(RecommendPermissionModel.ShareBean shareBean) {
		Intent intent = new Intent(getActivity(), LASScanRecommendActivity.class);
		intent.putExtra(LASScanRecommendActivity.URI, shareBean.url);
		intent.putExtra(LASScanRecommendActivity.CONTENT, shareBean.content);
		intent.putExtra(LASScanRecommendActivity.TITLE, shareBean.title);
		intent.putExtra(LASScanRecommendActivity.CODE, shareBean.code);
		intent.putExtra(LASScanRecommendActivity.LEFT_RECOMMEND_LAS_TIMES, shareBean.left);
		LASScanRecommendActivity.start(getActivity(), intent);
	}

	@Override
	public void getLASShareUrlSuccess(RecommendPermissionModel.ShareBean shareBean) {
		if (!TextUtils.isEmpty(shareBean.left) && Integer.valueOf(shareBean.left) > 0){
			goToLASScanRecommend(shareBean);
		}else{
			RecommendLasTimesOverTopActivity.start(getActivity());
		}
	}

	@Override
	public void lasShareNotOpen() {
		// 跳转敬请期待
		RecommendLasNoOpenActivity.start(getActivity());
	}

	@Override
	public void getLasShareUrlFailed(String tips) {
		showToast(tips);
	}

	//账号（任意类型）被禁用
	@Override
	public void getRcmPermissionNoPermission() {
		RcmPermissionHelper.getRcmPermissionNoPermission(getContext());
	}

	//用户类型为母账户
	@Override
	public void getRcmPermissionIsParentAccount() {
		RcmPermissionHelper.getRcmPermissionIsParentAccount(getContext());
	}

	//注册时填写公司编号，被母账号拒绝
	@Override
	public void getRcmPermissionNoBindCompany() {
		RcmPermissionHelper.getRcmPermissionNoBindCompany(getContext());
	}

	//注册时填写公司编号，母账号未处理申请
	@Override
	public void getRcmPermissionApplying() {
		RcmPermissionHelper.getRcmPermissionApplying(getContext());
	}

	//公司编号过期
	@Override
	public void getRcmPermissionChannelExpired(final String company, final String phone) {
		RcmPermissionHelper.getRcmPermissionChannelExpired(getContext(), company, phone);
	}

	//账户未经过实名认证
	@Override
	public void getRcmPermissionNoRealName() {
		RcmPermissionHelper.getRcmPermissionNoRealName(getContext());
	}

	@Override
	public void getRcmPermissionSuccess() {
		RcmPermissionHelper.getRcmPermissionSuccess(getContext());
	}


	@Override
	public void getRecommendPassFailure(String tips) {
		RcmPermissionHelper.getRecommendPassFailure(getContext(), tips);
	}

	@Override
	public void onGetBannerSuccess(List<BannerModel.BannerBean> data) {
		mBannerData = data;
		mAdapter.setImageList(data);
		mAdapter.notifyDataSetChanged();
		mAutoViewPager.setAdapter(mAdapter);
		mIndicator.setViewPager(mAutoViewPager, data.size());
		mAutoViewPager.setCurrentItem(0);
	}

	@Override
	public void onGetBannerFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void getToDoListSizeSuccess(String size) {
		resolveToDoListNum(size);
	}

	private void resolveToDoListNum(String size){
		if (Integer.valueOf(size) > 0) {
			mTodoListSize = size;
			mTodoListTipsTv.setText(size);
			mTodoListTipsTv.setVisibility(View.VISIBLE);
		} else {
			mTodoListTipsTv.setVisibility(View.GONE);
		}
	}

	@Override
	public void setMsgRead(boolean readFlag) {
		if (!readFlag) {
			mMsgRedDotView.setVisibility(View.VISIBLE);
		} else {
			mMsgRedDotView.setVisibility(View.GONE);
		}
	}

	@Override
	public void refreshMsgSuccess(List<MsgModel.MsgInfo> stationInfo) {

	}

	@Override
	public void loadMoreMsgSuccess(List<MsgModel.MsgInfo> stationInfo) {

	}

	@Override
	public void getMsgFailure() {

	}

	@Override
	public void selectedAd(BannerModel.BannerBean bannerBean) {
		if (!TextUtils.isEmpty(bannerBean.href)) {
			WebActivity.start(getActivity(), bannerBean);
		}
	}

	/**
	 * 获取banner.
	 */
	public void loadBanner() {
		if (mBannerData != null) {
			onGetBannerSuccess(mBannerData);
		} else if (mBannerPresenter != null) {
			mBannerPresenter.getBanner();
		}
	}
}